<template>
  <el-dialog :title="form.id?'编辑角色':'新增角色'" width="50%" :visible="dialogFormVisible" @close="close">
    <el-form ref="form" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="form.description" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="addRole">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addRoles, editRoles } from '@/api/roles'
export default {
  name: 'Dialog',
  model: {
    prop: 'dialogFormVisible'
  },
  props: {
    dialogFormVisible: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    close() {
      // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.$refs.form.resetFields()
      this.$emit('input', false)
    },
    async addRole() {
      await this.$refs.form.validate()
      if (this.form.id) {
        await editRoles(this.form)
        this.$message.success('修改成功')
      } else {
        await addRoles(this.form)
        this.$message.success('添加成功')
      }
      this.$emit('success')
      this.close()
    }
  }
}
</script>

<style scoped>

</style>
